// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Chronos.cs" company="Open Trader">
//   Copyright (c) David Denis (david.denis@systemathics.com)
// </copyright>
// <summary>
//   |  Open Trader - The Open Source Systematic Trading Platform
//   |
//   |  This program is free software: you can redistribute it and/or modify
//   |  it under the terms of the GNU General Public License as published by
//   |  the Free Software Foundation, either version 2 of the License, or
//   |  (at your option) any later version.
//   |
//   |  This program is distributed in the hope that it will be useful,
//   |  but WITHOUT ANY WARRANTY; without even the implied warranty of
//   |  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   |  GNU General Public License for more details.
//   |
//   |  You should have received a copy of the GNU General Public License
//   |  along with this program.  If not, see http://www.gnu.org/licenses
//   |
//   |  Up to date informations about Open Trader can be found at :
//   |    http://opentrader.org
//   |    http://opentrader.codeplex.com
//   |
//   |  For professional services, please visit us at :
//   |    http://www.systemathics.com
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Org.OpenTrader.Framework
{
    #region Using Directives

    using System;
    using System.Collections.Generic;

    using Org.OpenTrader.Framework.Interfaces;

    #endregion

    /// <summary>
    /// The chronos.
    /// </summary>
    public class Chronos : IChronos, IDisposable
    {
        #region Constants and Fields

        /// <summary>
        /// The MaxInvokers.
        /// </summary>
        private const int MaxInvokers = 2;

        /// <summary>
        /// The invokers.
        /// </summary>
        private readonly List<AbtractChronosWorker> invokers;

        // Number of workers that will handle pulsing of things. This is for load purpose

        /// <summary>
        /// The lock.
        /// </summary>
        private readonly Locker locker; // Internal locking  

        /// <summary>
        /// The invokersPos.
        /// </summary>
        private int invokersPos; // Current invoker index, this moves in [0,MaxInvokers-1]

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Chronos"/> class.
        /// </summary>
        public Chronos()
        {
            this.locker = new Locker();
            this.invokers = new List<AbtractChronosWorker>();
            this.invokersPos = 0;

            for (var i = 0; i < MaxInvokers; i++)
            {
#if ! DISABLE_NATIVE_CALLS

                // Precise
                var w = new ChronosWorkerWinMM();
#else
    
    // Imprecise
                var w = new ChronosWorkerDotNet(30, 15);
#endif
                this.invokers.Add(w);
                w.Start();
            }
        }

        #endregion

        #region Implemented Interfaces

        #region IChronos

        /// <summary>
        /// The add.
        /// </summary>
        /// <param name="callableable">
        /// The callableable.
        /// </param>
        /// <returns>
        /// The add.
        /// </returns>
        public bool Add(IPulsable callableable)
        {
            try
            {
                using (this.locker.Lock())
                {
                    this.invokersPos++;
                    this.invokersPos %= MaxInvokers;
                    this.invokers[this.invokersPos].Add(new PulsedInfo(callableable));
                    return true;
                }
            }
            catch (LockerTimeoutException)
            {
                // TODO ExceptionUtil.LogLockTimeoutException(null, te);
            }
            catch (Exception)
            {
                // TODO ExceptionUtil.LogException(null, e);
            }

            return false;
        }

        /// <summary>
        /// The remove.
        /// </summary>
        /// <param name="callableable">
        /// The callableable.
        /// </param>
        /// <returns>
        /// The remove.
        /// </returns>
        public bool Remove(IPulsable callableable)
        {
            try
            {
                using (this.locker.Lock())
                {
                    for (var i = 0; i < this.invokers.Count; i++)
                    {
                        if (this.invokers[i].Contains(new PulsedInfo(callableable)))
                        {
                            return this.invokers[i].Remove(new PulsedInfo(callableable));
                        }
                    }
                }
            }
            catch (LockerTimeoutException)
            {
                // TODO Exception reporting
            }
            catch (Exception)
            {
                // TODO Exception reporting
            }

            return false;
        }

        #endregion

        #region IDisposable

        /// <summary>
        /// The dispose.
        /// </summary>
        public void Dispose()
        {
            foreach (var w in this.invokers)
            {
                w.Stop();
            }

            this.invokers.Clear();
        }

        #endregion

        #endregion
    }
}